package com.cloudkinto.service.sms.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.common.DicBusinessItemConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.utils.StringsUtil;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.entity.DicBusinessItemDo;
import com.cloudkinto.service.sms.SmsService;
import com.cloudkinto.service.sms.vo.SmsAddRequest;
import com.cloudkinto.entity.SmsDo;
import com.cloudkinto.dao.SmsDao;
import com.cloudkinto.service.sms.SmsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * service实现类
 * </p>
 *
 * @author ding
 * @since 2023-08-17
 */
@Service
@Transactional(rollbackFor = Exception.class)//事务回滚
public class SmsServiceImpl extends ServiceImpl<SmsDao, SmsDo> implements SmsService {
    @Autowired
    private SmsDao dao;

    @Override
    public SingleResult addInit() {
        return SingleResult.success("");
    }

    @Override
    public String addBatch(List<SmsAddRequest> requestList, Long userId) {
        for (SmsAddRequest smsAddRequest : requestList) {
            try {
                add(smsAddRequest, userId);
            } catch (Exception e) {
                e.printStackTrace();
                return "error";
            }
        }
        return "save";
    }

    @Override
    public int add(SmsAddRequest req, Long userId) {
        SmsDo entityDo = new SmsDo();
        BeanUtils.copyProperties(req, entityDo);
        long msgId = Long.parseLong(req.getMsgId());
        LambdaQueryWrapper<SmsDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SmsDo::getMsgId, msgId);
        if (dao.selectCount(wrapper) > 0) {
            return 0;
        }
        entityDo.setMsgId(msgId);
        entityDo.setContent((req.getBody()));
        String address = req.getAddress().replaceAll(",", "").replaceAll(" ", "");
        try {
            if (address.equals("95555")
                //                && req.getAddress().equals("95555")
            ) {
                if (req.getBody().contains("国际业务")) {
                    if (req.getBody().contains("需要确认")) {
                        int i1 = req.getBody().indexOf("汇款（");
                        int i2 = req.getBody().indexOf("）需要确认");
                        //贵司业务编号为512IR232035856的汇入汇款
                        int i3 = req.getBody().indexOf("编号为");
                        int i4 = req.getBody().indexOf("的汇入汇款");
                        String amountAndCurrency = req.getBody().substring(i1 + 3, i2);
                        entityDo.setCurrency(getCurrencyTextOrId(amountAndCurrency, 1));
                        entityDo.setCurrencyId(Long.parseLong(getCurrencyTextOrId(amountAndCurrency, 0)));
                        entityDo.setAmount(Integer.parseInt(StringsUtil.getNumberPattern(amountAndCurrency)) * 100);
                        entityDo.setOutAccountName(req.getBody().substring(i3 + 3, i4) + "需要确认");
                    } else if (req.getBody().contains("成功入账")) {
                        int i1 = req.getBody().indexOf("汇款（");
                        int i2 = req.getBody().indexOf("）已成功");
                        int i3 = req.getBody().indexOf("编号为");
                        int i4 = req.getBody().indexOf("的汇入汇款");
                        String amountAndCurrency = req.getBody().substring(i1 + 3, i2);
                        entityDo.setCurrency(getCurrencyTextOrId(amountAndCurrency, 1));
                        entityDo.setCurrencyId(Long.parseLong(getCurrencyTextOrId(amountAndCurrency, 0)));
                        entityDo.setAmount(Integer.parseInt(StringsUtil.getNumberPattern(amountAndCurrency)) * 100);
                        entityDo.setOutAccountName(req.getBody().substring(i3 + 3, i4) + "成功入账");
                    }
                    entityDo.setReceiveTime(TimeUtils.parseDate(req.getDate(), "yyyy-MM-dd HH:mm:ss"));
                    entityDo.setPayTime(TimeUtils.parseDate(req.getDate(), "yyyy-MM-dd HH:mm:ss"));
                } else {
                    int i = req.getBody().indexOf(",于");
                    String inAccountName = req.getBody().substring(req.getBody().indexOf("户名") + 2, i);
                    if (!(StringUtils.isNotBlank(inAccountName) && inAccountName.contains("猫若"))) {

                        int i1 = req.getBody().indexOf("收到");
                        String payTime = req.getBody().substring(i + 2, i1);
                        int i2 = req.getBody().indexOf("余额为");
                        String amountAndCurrency = req.getBody().substring(i1 + 2, i2);
                        String outAccountName = req.getBody().substring(req.getBody().indexOf("付方账号") + 4);
                        entityDo.setCurrency(getCurrencyTextOrId(amountAndCurrency, 1));
                        entityDo.setCurrencyId(Long.parseLong(getCurrencyTextOrId(amountAndCurrency, 0)));
                        entityDo.setAmount(Integer.parseInt(StringsUtil.getNumberPattern(amountAndCurrency)));
                        entityDo.setReceiveTime(TimeUtils.parseDate(req.getDate(), "yyyy-MM-dd HH:mm:ss"));
                        entityDo.setPayTime(TimeUtils.parseDate(payTime, "yyyy年MM月dd日-HH:mm:ss"));
                        entityDo.setInAccount("512910168810601");
                        entityDo.setInAccountName(inAccountName);
                        entityDo.setOutAccount(StringsUtil.getNumberPattern(outAccountName));
                        entityDo.setOutAccountName(StringsUtil.getChinesePattern(outAccountName));
                    }
                }
            } else if (address.equals("95533")) {
                if (!req.getBody().contains("收入")) return 0;
                int i = req.getBody().indexOf("分");
                //            String inAccountName =
                int i1 = req.getBody().indexOf("收入");
                String payTime = TimeUtils.formatDate(new Date(), "yyyy年") + req.getBody().substring(req.getBody().indexOf("账户") + 2, i);
                int i2 = req.getBody().indexOf("元，可用余额");
                String amountAndCurrency = req.getBody().substring(i1, i2);
                String outAccountName = req.getBody().substring(req.getBody().indexOf("方户名:") + 4, req.getBody().indexOf("。["));
                entityDo.setCurrency(getCurrencyTextOrId(amountAndCurrency, 1));
                entityDo.setCurrencyId(Long.parseLong(getCurrencyTextOrId(amountAndCurrency, 0)));
                entityDo.setAmount(Integer.parseInt(StringsUtil.getNumberPattern(amountAndCurrency)));
                entityDo.setReceiveTime(TimeUtils.parseDate(req.getDate(), "yyyy-MM-dd HH:mm:ss"));
                entityDo.setPayTime(TimeUtils.parseDate(payTime, "yyyy年MM月dd日HH时mm"));
                entityDo.setInAccount("512910168810601");
                //            entityDo.setInAccountName(inAccountName);
                //            entityDo.setOutAccount(getNumberPattern(outAccountName));
                entityDo.setOutAccountName((outAccountName));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        handlerAddBefore(entityDo, userId);
        return dao.insert(entityDo);
    }

    private String getCurrencyTextOrId(String amountAndCurrency, int type) {
        if (amountAndCurrency.contains("日币") || amountAndCurrency.contains("日元")) {
            return type == 0 ? DicBusinessItemConstant.CurrencyTypeJpy + "" : "JPY";
        }
        if (amountAndCurrency.contains("美金") || amountAndCurrency.contains("美元")) {
            return type == 0 ? DicBusinessItemConstant.CurrencyTypeUsd + "" : "USD";
        }
        return type == 0 ? DicBusinessItemConstant.CurrencyTypeRmb + "" : "RMB";
    }

    //新增校验
    private void addCheck(Object req) {

    }

    //做新增之前要执行的业务定制处理
    private void handlerAddBefore(SmsDo entityDo, Long userId) {
        entityDo.setCreateBy(userId);
        entityDo.setCreateTime(new Date());
        entityDo.setDeleteFlag(SysConstant.DELETE_FLAG_FALSE);
    }

    //将新增的do转换成要返回的实体
    private Object handlerAddAfter(SmsDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public SingleResult updateInit(Long id) {
        return SingleResult.success("");
    }

    @Override
    public Object update(Object req, Long userId) {
        /*SmsDo entityDo = dao.selectById(req.getId());
        BeanUtils.copyProperties(req, entityDo);
        handlerUpdateBefore(entityDo, userId);
        dao.updateById(entityDo);
        return handlerUpdateAfter(entityDo);*/
        return null;
    }

    //编辑校验
    private void updateCheck(Object req) {

    }

    //做修改之前要执行的业务定制处理
    private void handlerUpdateBefore(SmsDo entityDo, Long userId) {
        entityDo.setUpdateBy(userId);
        entityDo.setUpdateTime(new Date());
    }

    //做修改之后要执行的业务定制处理
    private Object handlerUpdateAfter(SmsDo entityDo) {
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return res;
    }

    @Override
    public int delete(Long id, Long userId) {
        SmsDo entityDo = dao.selectById(id);
        handlerDeleteBefore(entityDo, userId);
        return dao.deleteById(id);
    }

    //做删除之前要执行的业务定制处理
    private void handlerDeleteBefore(SmsDo entityDo, Long userId) {
        entityDo.setDeleteBy(userId);
        entityDo.setDeleteTime(new Date());
    }

    @Override
    public Object detail(Long id) {
        SmsDo entityDo = dao.selectById(id);
        Object res = new Object();
        BeanUtils.copyProperties(entityDo, res);
        return handlerDetailAfter(res);
    }

    //查询明细之后要执行的业务定制处理
    private Object handlerDetailAfter(Object res) {
        return res;
    }

    @Override
    public SingleResult pageInit() {
        return SingleResult.success("");
    }

    @Override
    public List<Object> getList(Map<String, String> map) {
        QueryWrapper<SmsDo> wrapper = queryBuild(map);
        List<SmsDo> list = this.list(wrapper);
        List<Object> result = handlerListAfter(list);
        return result;
    }

    @Override
    public PageResult getListPage(Map<String, String> map) {
        QueryWrapper<SmsDo> wrapper = queryBuild(map);
        IPage<SmsDo> page = pageInit(map);
        page = this.page(page, wrapper);
        List<Object> resList = handlerListAfter(page.getRecords());
        PageResult result = new PageResult(resList, (int) page.getCurrent(), (int) page.getSize(), (int) page.getTotal(), (int) page.getPages());
        return result;
    }

    //查询分页列表之后对列表数据的处理
    private List<Object> handlerListAfter(List<SmsDo> list) {
        List<Object> result = new ArrayList<>();
        return result;
    }

    private IPage<SmsDo> pageInit(Map<String, String> map) {
        IPage<SmsDo> page = new Page();
        page.setSize(StringUtils.isNotBlank(map.get("pageSize")) ? Long.parseLong(map.get("pageSize")) : 10);
        page.setCurrent(StringUtils.isNotBlank(map.get("current")) ? Long.parseLong(map.get("current")) : 1);
        return page;
    }

    private QueryWrapper<SmsDo> queryBuild(Map<String, String> map) {
        QueryWrapper<SmsDo> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(map.get("keyword"))) {
            wrapper.like("keyword", map.get("keyword"));
        }
        return wrapper;
    }


}
